<?php

class Pager {
	
	var $currentPage = 0;
	var $pageSize = 20;
	var $nextPage = 0;
	var $lastPage = 0;
	var $isFirstPage = true;
	var $isLastPage = true;
	var $totalPages;
	var $totalItems;
	var $pageSql;
	var $db;
	
	function Pager($option) {
		$pSize = $option['pageSize'];
		$sql = trim($option['sql']);
		$cId = $option['currentId'];
		
		if (!isset($cId) || $cId <= 0 ) {
			$cId = 1;
		}
	
		$this->currentPage = $cId;
		
	    if (isset($pSize)) {
			$this->pageSize = $pSize;
		}
		$this->db = $option['db'];
		$this->db->Query($sql);
		$this->totalItems = $this->db->getNum();
		
		if ($this->totalItems > 0) {
			if ($this->totalItems < $this->pageSize) {
				$this->totalPages = 1;
			} elseif ($this->totalItems % $this->pageSize){
				$this->totalPages= (int)($this->totalItems / $this->pageSize) + 1;
			} else {
				$this->totalPages= $this->totalItems / $this->pageSize;
			}
		} else {
			$this->totalPages = 0;
			return false;
		}
		
		
		if ($sql[strlen($sql)-1]==';') {
			$sql = substr ($sql,0,strlen($sql)-1);
		}
		
		$from = ($this->currentPage - 1)*$this->pageSize;
		$this->pageSql = $sql." limit ".$from.", ".$this->pageSize;
		
		if ($this->totalPages == 1) {
			$this->isFirstPage = true;
	        $this->isLastPage = true;
		} elseif ($this->currentPage == 1) {
			$this->isFirstPage = true;
	        $this->isLastPage = false;
		} elseif ($this->currentPage == $this->totalPages) {
			$this->isFirstPage = false;
	        $this->isLastPage = true;
		} else {
			$this->isFirstPage = false;
            $this->isLastPage = false;
		}
	
	    if ( $this->totalPages > 1 ){
	      if ( !$this->isLastPage ) { $this->nextPage = $this->currentPage + 1; }
	      if ( !$this->isFirstPage ) { $this->lastPage = $this->currentPage - 1; }
	    }
	    
	    return true;
		
	}
	
	function getPageData() {
		$array = array();
		
		if ($this->totalItems == 0) {
			return false;
		}
		
		$array['currentPage']=$this->currentPage;
		$array['pageSize']=$this->pageSize;
		$array['nextPage']=$this->nextPage;
		$array['lastPage']=$this->lastPage;
		$array['isFirstPage']=$this->isFirstPage;
		$array['isLastPage']=$this->isLastPage;
		$array['totalPages']=$this->totalPages;
		$array['totalItems']=$this->totalItems;
		$array['pageData']=$this->db->Query($this->pageSql);
		
		return $array;
		
	}
	
}


?>